package com.briup.service.impl;

import com.briup.bean.ShopCar;
import com.briup.dao.CustomerMapper;
import com.briup.dao.ShopCarMapper;
import com.briup.service.IShopCarService;
import com.briup.util.MyBatisSqlSessionFactory;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ShopCarServiceImpl implements IShopCarService {
    SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
    ShopCarMapper mapper = sqlSession.getMapper(ShopCarMapper.class);
    @Override
    public void saveShopCar(ShopCar sc) {
//        先要判断 我现在加入购物车的这本书 在购物车表里面有没有
        //        根据用户id和书籍id来查询数据库当中 该用户有没有添加过该书本的记录
        ShopCar shopCar = mapper.queryShopCarByCidAndBId(sc.getCustomerId(),sc.getBookId());
//        mapper.updateShopCar();
        if(shopCar!=null){
            //        如果有的话 更新num
//            旧的数量+新的数量
            int sum = shopCar.getNum() + sc.getNum();
            shopCar.setNum(sum);
            mapper.updateShopCar(shopCar);
        }else{
            mapper.saveShopCar(sc);
        }
        sqlSession.commit();
//        如果没有的话
//                直接添加一条新纪录
//        mapper.saveShopCar();
    }

    @Override
    public void updateShopCar(ShopCar sc) {
        mapper.updateShopCar(sc);
        sqlSession.commit();
    }

    @Override
    public ShopCar queryShopCarByCidAndBId(int cid, int bid) {
        return null;
    }

    @Override
    public List<ShopCar> findShopCarsByCustomer(Integer id) {
        return mapper.findShopCarsByCustomer(id);
    }

    @Override
    public void deleteShopCarByCidAndBId(int cid, int bid) {
        mapper.deleteShopCarByCidAndBId(cid,bid);
        sqlSession.commit();
    }

    @Override
    public void deleteShopCarByCustomerId(int cid) {
        mapper.deleteShopCarByCustomerId(cid);
        sqlSession.commit();
    }
}
